<?php

namespace ticket\modules\frontend\models;

use ticket\libs\Tools;
use Yii;

/**
 * This is the model class for table "tk_order_info".
 *
 * @property int $oid
 * @property int $tid
 * @property int $app_id
 * @property int $aid
 * @property string $goods_name
 * @property string $order_number
 * @property string $refund_number
 * @property int $goods_num
 * @property string $pay_type
 * @property int $order_amount
 * @property int $real_pay
 * @property int $order_status
 * @property string $is_write_off
 * @property string $is_finish
 * @property string $self_status
 * @property string $from
 * @property string $pay_note
 * @property string $pay_time
 * @property string $create_time
 */
class OrderInfo extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'tk_order_info';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['tid', 'app_id', 'aid', 'goods_name', 'order_number','openid'], 'required'],
            [['tid', 'app_id', 'aid', 'goods_num', 'order_amount', 'real_pay', 'order_status','is_list'], 'number'],
            [['is_write_off', 'is_finish', 'self_status','ticket_json'], 'string'],
            [['pay_time', 'create_time'], 'safe'],
            [['goods_name', 'from'], 'string', 'max' => 64],
            [['order_number', 'refund_number', 'pay_type','openid'], 'string', 'max' => 32],
            [['pay_note'], 'string', 'max' => 1024],
            [['share_member_id'], 'string', 'max' => 100]
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'oid' => 'Oid',
            'tid' => 'Tid',
            'app_id' => 'App ID',
            'aid' => 'Aid',
            'goods_name' => 'Goods Name',
            'order_number' => 'Order Number',
            'refund_number' => 'Refund Number',
            'goods_num' => 'Goods Num',
            'pay_type' => 'Pay Type',
            'order_amount' => 'Order Amount',
            'real_pay' => 'Real Pay',
            'order_status' => 'Order Status',
            'is_write_off' => 'Is Write Off',
            'is_finish' => 'Is Finish',
            'self_status' => 'Self Status',
            'from' => 'From',
            'pay_note' => 'Pay Note',
            'pay_time' => 'Pay Time',
            'create_time' => 'Create Time',
        ];
    }


    public function addOrderInfo($params,$orderSn)
    {
        $data = $this->setData($params,$orderSn);
       if ($this->load($data) and $this->validate()){
           if ($this->save(0)){
               return $this->primaryKey;
           }
       }
       return false;
    }

    /** 获取订单信息
     * @param $orderNum     订单号
     * @param $appId        实例id
     * @param $openId       openid
     * @return array|null|\yii\db\ActiveRecord
     */
    public function getInfo($orderNum,$appId,$openId)
    {
        $data = self::find()->where(['order_number' => $orderNum,'app_id' => $appId])->asArray()->one();
        return $data;
    }

    /*** 设置订单状态
     * @param $orderNum
     * @param $appId
     * @param $status
     * @return bool
     */
    public function setInfo($orderNum,$appId,$status,$refund_number = '')
    {
        $model = self::find()->where(['order_number' => $orderNum,'app_id' => $appId])->one();
        if (!is_null($model)){
            $model->order_status = $status;
            $model->refund_number = $refund_number;
            if ($model->save(0)){
                return true;
            }
        }
        return false;
    }


    /*** 获取用户订单列表
     * @param $openid
     * @param $post
     * @return array
     */
    public static function orderInfo($openid,$post)
    {
        if (isset($post['order_status']) and !empty($post['order_status'])){
            if ($post['order_status'] == 4){
                $whereStatus = ['or','order_status=4','order_status=7'];
            }else{
                $whereStatus = ['order_status' => $post['order_status']];
            }
        }else{
            $whereStatus = [];
        }
        if (isset($post['goods_name']) and !empty($post['goods_name'])){
            $whereName = ['like','goods_name',$post['goods_name']];
        }else{
            $whereName = [];
        }

        $page = isset($post['page'])?$post['page']:1;
        $size = isset($post['size'])?$post['size']:10;

        $searchModel = OrderInfo::find()->where(['openid' => $openid])->andFilterWhere($whereName)->andFilterWhere($whereStatus);
        $count = $searchModel->count();
        $orderList = $searchModel->offset($size * ($page - 1))->joinWith(['ticket'])->orderBy(['oid' => SORT_DESC])->asArray()->limit($size)->all();

        foreach ($orderList as $key => $val){
            if (!empty($val['ticket']) and !empty($val['ticket']['image_url'])){
                $orderList[$key]['goods_image'] = json_decode($val['ticket']['image_url'],true)[0]['url'];
            }else{
                $orderList[$key]['goods_image'] = '';
            }
			$orderList[$key]['ticket_json'] = json_decode($val['ticket_json'],true);
			if($orderList[$key]['ticket_json']){
				foreach($orderList[$key]['ticket_json'] as $k=>$v){
					$info = TicketInfo::find()->where(['or',['now_ticket_sn'=>$v['ticket_sn']],['ticket_sn'=>$v['ticket_sn']]])->asArray()->one();
					$orderList[$key]['ticket_json'][$k]['category'] = $info?$info['category']:'';
				}
			}
			
            $orderList[$key]['order_amount'] = $val['order_amount'] / 100;
            $orderList[$key]['real_pay'] = $val['real_pay'] / 100;
            unset($orderList[$key]['ticket']);
        }
        return [
            'orderList' => $orderList,
            'page' => $page,
            'count' => $count,
            'size' => $size,
        ];
    }


    public static function payOrderInfo($openid,$orderId)
    {
        $orderInfo =  self::find()->where('tk_order_info.oid = :id',[':id' => $orderId])->
        joinWith(['details'])->asArray()->one();
        $orderInfo['openid'] = $openid;
        return $orderInfo;
    }

    public function getOrderInfo($oid)
    {
        $data = self::find()->where('tk_order_info.oid = :id',[':id' => $oid])->joinWith(['details'])->asArray()->one();

        $data['discount'] = ($data['order_amount'] - $data['real_pay'])/100;  // 订单折扣
        $data['order_amount'] = $data['order_amount'] / 100;                       // 原价
        $data['real_pay'] = $data['real_pay'] / 100;                              // 现价
        return $data;
    }


    public function getDetails()
    {
        $data = $this->hasOne(OrderDetails::className(),['oid' => 'oid']);
        return $data;
    }

    public function getTicket()
    {
        $data = $this->hasOne(TicketAdditional::className(),['tid' => 'tid'])->select(['tid','image_url']);
        return $data;
    }








    public function setData($params,$orderSn)
    {
		//区分是否是购物车
		if($params['postData']['is_list']){
			$data['OrderInfo']['tid'] = 0;
			$data['OrderInfo']['goods_name'] = '一日票';
			$data['OrderInfo']['goods_num'] = $params['all_num'];
			$data['OrderInfo']['is_list'] = 1;
			$data['OrderInfo']['ticket_json'] = json_encode($params['ticket_json']);
		}else{
			$data['OrderInfo']['tid'] = $params['tid'];
			$data['OrderInfo']['goods_name'] = $params['name'];
			$data['OrderInfo']['goods_num'] = $params['postData']['num'];
			$data['OrderInfo']['is_list'] = 0;
		}
        
        $data['OrderInfo']['aid'] = $params['aid'];
        $data['OrderInfo']['app_id'] = $params['app_id'];
        $data['OrderInfo']['openid'] = $params['postData']['openid'];
        
        $data['OrderInfo']['order_number'] = $orderSn;
        
        $data['OrderInfo']['pay_type'] = isset($params['postData']['pay_type'])?$params['postData']['pay_type']:'微信';
        $data['OrderInfo']['order_amount'] = $params['total_price'] * 100;
        $data['OrderInfo']['real_pay'] = 0;
        $data['OrderInfo']['order_status'] = 1;
        $data['OrderInfo']['is_write_off'] = '1';
        $data['OrderInfo']['is_finish'] = '2';
        $data['OrderInfo']['self_status'] = '1';
        $data['OrderInfo']['from'] = '小程序';
        $data['OrderInfo']['pay_note'] = '';
        $data['OrderInfo']['pay_time'] = '0000-00-00 00:00:00';
        $data['OrderInfo']['create_time'] = date("Y-m-d H:i:s");
        $data['OrderInfo']['share_member_id'] = $params['postData']['share_member_id'];

        if (isset($params['postData']['coupon_name']) and !empty($params['postData']['coupon_name'])){ // 使用优惠券
            $pay_note = [
                'coupon_name' => $params['postData']['coupon_name'],
                'coupon_id' => $params['postData']['coupon_id'],
            ];  // 如果使用优惠券的话，记录优惠券名称和id；
            $data['OrderInfo']['pay_note'] = json_encode($pay_note,JSON_UNESCAPED_UNICODE);
        }elseif ($params['postData']['coupon_from'] == 3 and !empty($params['postData']['coupons_type'])){
            $pay_note = [
                'coupon_name' => '年卡折扣',
                'coupons_type' => $params['postData']['coupons_type'],
                'discount' => $params['postData']['discount'],
            ];  // 如果使用优惠券的话，记录优惠券名称和id；
            $data['OrderInfo']['pay_note'] = json_encode($pay_note,JSON_UNESCAPED_UNICODE);
        }
        return $data;
    }






}
